Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.
a) What percentage of the first 100 images in human_files have a detected human face?
b) What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: a) 96.00% b) 11.00%

In [5]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
human_faces_len = len(human_files_short)
detected_human_faces_cnt = sum([face_detector(human_face) for human_face in human_files_short])
print("number of detected human faces in human files: {:.2f}%".format(detected_human_faces_cnt*100/human_faces_len))
dog_faces_len = len(dog_files_short)
detected_human_faces_from_dogs_cnt = sum([face_detector(dog_face) for dog_face in dog_files_short])
print("number of detected human faces in dog files: {:.2f}%".format(detected_human_faces_from_dogs_cnt*100/dog_faces_len))
number of detected human faces in human files: 96.00%
number of detected human faces in dog files: 11.00%

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: It is reasonable to ask for images of faces to have a clear view of the face as this firmly sets an expectation vs reality paradigm for expected performance. Given that there is a communication that the algorithm performs best on clearly presented faces, there are clear expectations set up that if they do not provide an acceptable image they should not expect accurate results. If there was no communication, then it would be unreasonable to expect users to provide clear facial images.

To try improve detect faces for non-clear images, filters could be applied that detect edges so that the principle features of a face could be seen with lesser regard for lighting; for angled images, the image could be disorted to try straighten it (if edges were measured to be non-existent across facial hemispheres), or the most clear side could be straightened and mirrored (as humans have fairly symmetrical faces).

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [6]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [7]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [8]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [9]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [10]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.
a) What percentage of the images in human_files_short have a detected dog?
b) What percentage of the images in dog_files_short have a detected dog?

Answer: a) 0.00% b) 100.00%

In [11]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.)
detected_dog_faces_from_humans_cnt = sum([dog_detector(human_face) for human_face in human_files_short])
print("number of detected human faces in human files: {:.2f}%".format(detected_dog_faces_from_humans_cnt*100/human_faces_len))
detected_dog_faces_cnt = sum([dog_detector(dog_face) for dog_face in dog_files_short])
print("number of detected human faces in dog files: {:.2f}%".format(detected_dog_faces_cnt*100/dog_faces_len))
number of detected human faces in human files: 0.00%
number of detected human faces in dog files: 100.00%

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [12]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [00:35<00:00, 187.17it/s]
100%|██████████| 835/835 [00:04<00:00, 193.88it/s]
100%|██████████| 836/836 [00:04<00:00, 196.65it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

1) The first time I trained the model using the architecture from the image, but got an accuracy of ~0.9%

2) After reading that Max pooling works better in practice than Average pooling, I adjusted the model to be as in the sample image, but with a max instead of average pooling layer, to see if this does work better in practice. This got an accuracy of ~2%

3) I then took the end architecture from another model from the course (with a different softmax layer due to number of possibilities of course):

model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(133, activation='softmax'))

but the Dense(500) caused a large number of parameters in the model that seemed unnecessarily complicated (25,159,581.0). This did get an accuracy of 8.5% though.

4) I used a GlobalMaxPooling instead of Flatten and Dense(250) instead of Dense(500), but accuracy dropped to 2.66%

5) Returning to Flatten() improved accuracy to 7.9%

6) Reduced Dropout layers as I figured we weren't worried about overfitting if accuracy is so low, but accuracy decreased to 4.5%, so returned to their previous values.

7) Tried to change initial (layer 1) number of filters from 16 to 64, and this changed accuracy to 10.52%, which I was happy with.

In [13]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, GlobalMaxPooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', 
                        input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(250, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(133, activation='softmax'))
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 224, 224, 64)      832       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 112, 112, 64)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 112, 112, 32)      8224      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 56, 56, 64)        8256      
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 28, 28, 64)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 28, 28, 64)        0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 50176)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 250)               12544250  
_________________________________________________________________
dropout_2 (Dropout)          (None, 250)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               33383     
=================================================================
Total params: 12,594,945.0
Trainable params: 12,594,945.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [14]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [15]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 5

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=0, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/5
6680/6680 [==============================] - 53s - loss: 4.8854 - acc: 0.0112 - val_loss: 4.6870 - val_acc: 0.0323
Epoch 2/5
6680/6680 [==============================] - 52s - loss: 4.5046 - acc: 0.0467 - val_loss: 4.3762 - val_acc: 0.0635
Epoch 3/5
6680/6680 [==============================] - 52s - loss: 3.9670 - acc: 0.1073 - val_loss: 4.1646 - val_acc: 0.0754
Epoch 4/5
6680/6680 [==============================] - 52s - loss: 3.2836 - acc: 0.2310 - val_loss: 4.2627 - val_acc: 0.0671
Epoch 5/5
6680/6680 [==============================] - 52s - loss: 2.3990 - acc: 0.4003 - val_loss: 4.6999 - val_acc: 0.0874
Out[15]:
<keras.callbacks.History at 0x7f41e2532a20>

Load the Model with the Best Validation Loss

In [16]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [17]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 9.2105%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [18]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [19]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [20]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [21]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6620/6680 [============================>.] - ETA: 0s - loss: 12.5335 - acc: 0.1005Epoch 00000: val_loss improved from inf to 10.73357, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 12.5124 - acc: 0.1015 - val_loss: 10.7336 - val_acc: 0.2204
Epoch 2/20
6640/6680 [============================>.] - ETA: 0s - loss: 10.0243 - acc: 0.2756Epoch 00001: val_loss improved from 10.73357 to 9.88088, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 10.0215 - acc: 0.2759 - val_loss: 9.8809 - val_acc: 0.2886
Epoch 3/20
6660/6680 [============================>.] - ETA: 0s - loss: 9.4461 - acc: 0.3474Epoch 00002: val_loss improved from 9.88088 to 9.75210, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 4s - loss: 9.4430 - acc: 0.3476 - val_loss: 9.7521 - val_acc: 0.3114
Epoch 4/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.2333 - acc: 0.3812Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 9.2485 - acc: 0.3802 - val_loss: 9.7774 - val_acc: 0.3234
Epoch 5/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.1491 - acc: 0.3979Epoch 00004: val_loss improved from 9.75210 to 9.60298, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 4s - loss: 9.1394 - acc: 0.3981 - val_loss: 9.6030 - val_acc: 0.3377
Epoch 6/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.9004 - acc: 0.4169Epoch 00005: val_loss improved from 9.60298 to 9.28665, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 4s - loss: 8.8947 - acc: 0.4169 - val_loss: 9.2867 - val_acc: 0.3557
Epoch 7/20
6660/6680 [============================>.] - ETA: 0s - loss: 8.6318 - acc: 0.4386Epoch 00006: val_loss improved from 9.28665 to 9.03205, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 4s - loss: 8.6397 - acc: 0.4382 - val_loss: 9.0320 - val_acc: 0.3653
Epoch 8/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.5091 - acc: 0.4545Epoch 00007: val_loss improved from 9.03205 to 8.96730, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 8.5020 - acc: 0.4548 - val_loss: 8.9673 - val_acc: 0.3856
Epoch 9/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.4035 - acc: 0.4638Epoch 00008: val_loss improved from 8.96730 to 8.91061, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 4s - loss: 8.3985 - acc: 0.4644 - val_loss: 8.9106 - val_acc: 0.3880
Epoch 10/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.3366 - acc: 0.4687Epoch 00009: val_loss improved from 8.91061 to 8.83676, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 8.3248 - acc: 0.4693 - val_loss: 8.8368 - val_acc: 0.4072
Epoch 11/20
6660/6680 [============================>.] - ETA: 0s - loss: 8.2036 - acc: 0.4781Epoch 00010: val_loss improved from 8.83676 to 8.73929, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 8.2104 - acc: 0.4777 - val_loss: 8.7393 - val_acc: 0.4108
Epoch 12/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.1027 - acc: 0.4845Epoch 00011: val_loss improved from 8.73929 to 8.58784, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 8.0982 - acc: 0.4849 - val_loss: 8.5878 - val_acc: 0.4024
Epoch 13/20
6660/6680 [============================>.] - ETA: 0s - loss: 8.0331 - acc: 0.4899Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 8.0356 - acc: 0.4898 - val_loss: 8.6092 - val_acc: 0.4144
Epoch 14/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.0198 - acc: 0.4945Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 8.0086 - acc: 0.4952 - val_loss: 8.6078 - val_acc: 0.4180
Epoch 15/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.9707 - acc: 0.4980Epoch 00014: val_loss improved from 8.58784 to 8.54108, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 4s - loss: 7.9651 - acc: 0.4982 - val_loss: 8.5411 - val_acc: 0.4192
Epoch 16/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.8371 - acc: 0.5033Epoch 00015: val_loss improved from 8.54108 to 8.50011, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 4s - loss: 7.8386 - acc: 0.5031 - val_loss: 8.5001 - val_acc: 0.4240
Epoch 17/20
6640/6680 [============================>.] - ETA: 0s - loss: 7.7861 - acc: 0.5087Epoch 00016: val_loss improved from 8.50011 to 8.43889, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 7.7811 - acc: 0.5090 - val_loss: 8.4389 - val_acc: 0.4084
Epoch 18/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.5848 - acc: 0.5124Epoch 00017: val_loss improved from 8.43889 to 8.21888, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 7.5819 - acc: 0.5127 - val_loss: 8.2189 - val_acc: 0.4251
Epoch 19/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.3951 - acc: 0.5221Epoch 00018: val_loss improved from 8.21888 to 8.14144, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 5s - loss: 7.3947 - acc: 0.5222 - val_loss: 8.1414 - val_acc: 0.4359
Epoch 20/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.3341 - acc: 0.5341Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 7.3303 - acc: 0.5344 - val_loss: 8.1769 - val_acc: 0.4311
Out[21]:
<keras.callbacks.History at 0x7f41e20e8ef0>

Load the Model with the Best Validation Loss

In [22]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [23]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 43.6603%

Predict Dog Breed with the Model

In [24]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [25]:
### Create dictionaries for storing multiple bottleneck features
all_networks = ['VGG16','VGG19','Resnet50','InceptionV3','Xception']
if 'train_' in locals() or 'train_' in globals():
    print('exists')
else:
    train_ = {}
    valid_ = {}
    test_ = {}
    model_ = {}
    predictions_ = {}
In [26]:
### Obtain bottleneck features from another pre-trained CNN.
network=all_networks[2]
def get_bottleneck_features(network):
    bottleneck_features = np.load('bottleneck_features/Dog{}Data.npz'.format(network))
    train_[network] = bottleneck_features['train']
    valid_[network] = bottleneck_features['valid']
    test_[network] = bottleneck_features['test']
get_bottleneck_features(network)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

1) The intial accuracy on VGG16, with GlobalAveragePooling2D was 45%. This approach of choosing VGG16 was done to see what could be changed to improve the transfer learning in principle.

2) I took the best performing end part of the 'from scratch' network and put it at the end, but this abysmally had an accuracy of ~9% (ouch)

3) Replaced Flatten with GlobalMaxPooling2D as I suspected the Flatten may have caused this great loss of accuracy, but it was further decreased to 3%

4) Removed the Dense(250) layer, and accuracy was 4.5%

5) kept Dense layer, but removed Dropout and accuracy was 1% !!

6) Things were not looking good on the VGG16 dataset (steps above), so shifted to Resnet50 base network for transfer learning. The 'default' accuracy was ~81%.

7) Again hoping Max pooling would be more succesful, so replaced GlobalAveragePooling with GlobalMaxPooling for an accuracy of ~79%

8) Adding a Dropout of 0.4 to try reduce overfitting improved accuracy slightly to ~82%

9) Adding a fully connected Dense(1024) layer and a Dropout layer decreased accuracy to ~77%, so adding this complexity was clearly too extreme. I had also mistakenly made the non-final Dense layer to have a softmax activation function which caused an accuracy of 15%. As ReLU backpropagates better, I corrected quickly.

10) (Final) I finally decided that a GlobalAveragePooling with a Dropout to the Dense output layer performs the best for this small subset of exploration. Adding complex fully connected layers did not improve performance. Final best performance was ~82.7%

In [27]:
### Define model architecture
def create_model(network):
    model_[network] = Sequential()
    model_[network].add(GlobalAveragePooling2D(input_shape=train_[network].shape[1:]))
#     model_[network].add(GlobalMaxPooling2D(input_shape=train_[network].shape[1:]))
    model_[network].add(Dropout(0.4))
    model_[network].add(Dense(133, activation='softmax'))

    model_[network].summary()
create_model(network)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 2048)              0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 2048)              0         
_________________________________________________________________
dense_4 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [28]:
def compile_model(network):
    model_[network].compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
compile_model(network)

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [29]:
def train_model(network='VGG16',verbose=1):
    checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.transfer_{}.hdf5'.format(network), 
                                   verbose=verbose, save_best_only=True)

    model_[network].fit(train_[network], train_targets, 
              validation_data=(valid_[network], valid_targets),
              epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
train_model(network,0)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 4s - loss: 2.1136 - acc: 0.4904 - val_loss: 0.8479 - val_acc: 0.7377
Epoch 2/20
6680/6680 [==============================] - 4s - loss: 0.6834 - acc: 0.7879 - val_loss: 0.7324 - val_acc: 0.7760
Epoch 3/20
6680/6680 [==============================] - 4s - loss: 0.4893 - acc: 0.8473 - val_loss: 0.6538 - val_acc: 0.8072
Epoch 4/20
6680/6680 [==============================] - 4s - loss: 0.3827 - acc: 0.8795 - val_loss: 0.6784 - val_acc: 0.7904
Epoch 5/20
6680/6680 [==============================] - 4s - loss: 0.3281 - acc: 0.8975 - val_loss: 0.6694 - val_acc: 0.8060
Epoch 6/20
6680/6680 [==============================] - 4s - loss: 0.2869 - acc: 0.9102 - val_loss: 0.6468 - val_acc: 0.8132
Epoch 7/20
6680/6680 [==============================] - 4s - loss: 0.2679 - acc: 0.9190 - val_loss: 0.6473 - val_acc: 0.8192
Epoch 8/20
6680/6680 [==============================] - 4s - loss: 0.2345 - acc: 0.9249 - val_loss: 0.6479 - val_acc: 0.8192
Epoch 9/20
6680/6680 [==============================] - 4s - loss: 0.2115 - acc: 0.9317 - val_loss: 0.6895 - val_acc: 0.8180
Epoch 10/20
6680/6680 [==============================] - 4s - loss: 0.1930 - acc: 0.9356 - val_loss: 0.6603 - val_acc: 0.8144
Epoch 11/20
6680/6680 [==============================] - 4s - loss: 0.1840 - acc: 0.9428 - val_loss: 0.6725 - val_acc: 0.8240
Epoch 12/20
6680/6680 [==============================] - 4s - loss: 0.1796 - acc: 0.9476 - val_loss: 0.7233 - val_acc: 0.8323
Epoch 13/20
6680/6680 [==============================] - 4s - loss: 0.1595 - acc: 0.9510 - val_loss: 0.7093 - val_acc: 0.8192
Epoch 14/20
6680/6680 [==============================] - 4s - loss: 0.1681 - acc: 0.9487 - val_loss: 0.7175 - val_acc: 0.8323
Epoch 15/20
6680/6680 [==============================] - 4s - loss: 0.1418 - acc: 0.9542 - val_loss: 0.7184 - val_acc: 0.8287
Epoch 16/20
6680/6680 [==============================] - 4s - loss: 0.1422 - acc: 0.9593 - val_loss: 0.7009 - val_acc: 0.8275
Epoch 17/20
6680/6680 [==============================] - 4s - loss: 0.1292 - acc: 0.9627 - val_loss: 0.7497 - val_acc: 0.8275
Epoch 18/20
6680/6680 [==============================] - 4s - loss: 0.1135 - acc: 0.9650 - val_loss: 0.7563 - val_acc: 0.8275
Epoch 19/20
6680/6680 [==============================] - 4s - loss: 0.1136 - acc: 0.9642 - val_loss: 0.7506 - val_acc: 0.8323
Epoch 20/20
6680/6680 [==============================] - 4s - loss: 0.1169 - acc: 0.9639 - val_loss: 0.7984 - val_acc: 0.8228

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [30]:
def load_weights(network):
    model_[network].load_weights('saved_models/weights.best.transfer_{}.hdf5'.format(network))
load_weights(network)

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [31]:
def test_model_accuracy(network):
    # get index of predicted dog breed for each image in test set
    predictions_[network] = [np.argmax(model_[network].predict(np.expand_dims(feature, axis=0))) for feature in test_[network]]

    # report test accuracy
    test_accuracy = 100*np.sum(np.array(predictions_[network])==np.argmax(test_targets, axis=1))/len(predictions_[network])
    print('Test accuracy: %.4f%%' % test_accuracy)
test_model_accuracy(network)
Test accuracy: 80.3828%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [32]:
### function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
def predict_breed(img_path, network):
    extract_model = [extract_VGG16,extract_VGG19,extract_Resnet50,extract_InceptionV3,extract_Xception]\
                        [all_networks.index(network)]
    # extract bottleneck features
    bottleneck_feature = extract_model(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = model_[network].predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [33]:
def what_dog_breed(img_path, network):
    # load image
    img = cv2.imread(img_path)
    # convert BGR image to RGB for plotting
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # display the image
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.imshow(cv_rgb)
    # Detectors
    if dog_detector(img_path):
        ax.set_title('Dog detected!')
    elif face_detector(img_path):
        ax.set_title('Human face detected!')
    else:
        ax.set_title('No dog or human detected!\nTrying anyway...')
    # display prediction
    prediction = predict_breed(img_path, network)
    ax.set_xlabel('Detected dog breed is {}'.format(prediction))
    print(prediction)
    plt.show()
what_dog_breed('images/Human_Pam.jpg','Resnet50')
English_toy_spaniel

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: At least 1 algorithm (Resnet50) performed better than I expected with some none obvious images being predicted (such as the supplied images), and others images not expecting to be accurately predicted (the user-supplied Duschund and dog on human's laps).

Funny enough, InceptionV3, using the same architecture that I played around with for Resnet50 and VGG16, got a ~2% success rate, and predicted most images as having a Norwich Terrier. This was worse than expected, a lot worse.

Improvements could be done by

1) Having a larger training set of images, and possible dog breed labels, could improve the range of dog breeds as well as provide better discriminiation between breeds.

2) Augmenting the training images could improve performance by creating more invariant representations in the network.

3) Outputting probabilties for different breeds instead of a single breed classification would also imrpove the overall performance, as at least knowing it came close to a similar breed (but slightly less confident) is worthwhile knowledge. Further, this helps with mix-breeds! I see this is actually an exercise! I shall definitely attempt to refine the network according to recommended extensions of the project.

In [34]:
import glob

def test_algorithm(network,directory='images'):
    test_images = glob.glob("{}/*".format(directory))
    print("Using network based on {}".format(network))
    for test_image in test_images:
        print("-"*10+"\nAssessing file '{}'".format(test_image))
        what_dog_breed(test_image, network)
        print()
test_algorithm(network)
Using network based on Resnet50
----------
Assessing file 'images/Labrador_retriever_06455.jpg'
Chesapeake_bay_retriever
----------
Assessing file 'images/sample_dog_output.png'
Greyhound
----------
Assessing file 'images/Human_Pam.jpg'
English_toy_spaniel
----------
Assessing file 'images/Dog_Daschund.jpg'
German_pinscher
----------
Assessing file 'images/dog_on_humans.jpg'
Belgian_sheepdog
----------
Assessing file 'images/human_chris.jpg'
Akita
----------
Assessing file 'images/sample_cnn.png'
Australian_terrier
----------
Assessing file 'images/Labrador_retriever_06457.jpg'
Labrador_retriever
----------
Assessing file 'images/Welsh_springer_spaniel_08203.jpg'
Welsh_springer_spaniel
----------
Assessing file 'images/sample_human_output.png'
English_toy_spaniel
----------
Assessing file 'images/Curly-coated_retriever_03896.jpg'
Curly-coated_retriever
----------
Assessing file 'images/American_water_spaniel_00648.jpg'
American_water_spaniel
----------
Assessing file 'images/Brittany_02625.jpg'
Brittany
----------
Assessing file 'images/human_holding_dog.jpg'
Chihuahua
----------
Assessing file 'images/Labrador_retriever_06449.jpg'
Labrador_retriever

In [35]:
print(all_networks)
if 'already_trained' not in locals() and 'already_trained' not in globals():
    already_trained = network
for network in all_networks[1:]:
    if already_trained == network:
        print("already trained {}".format(network))
        continue
    print("*"*30+"\nCreating network based on {}\n".format(network)+"*"*30)
    get_bottleneck_features(network)
    create_model(network)
    compile_model(network)
    train_model(network,verbose=0)
    load_weights(network)
    test_model_accuracy(network)
    test_algorithm(network)
['VGG16', 'VGG19', 'Resnet50', 'InceptionV3', 'Xception']
******************************
Creating network based on VGG19
******************************
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 512)               0         
_________________________________________________________________
dropout_4 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 9s - loss: 13.8781 - acc: 0.0530 - val_loss: 11.2487 - val_acc: 0.1641
Epoch 2/20
6680/6680 [==============================] - 5s - loss: 11.8050 - acc: 0.1460 - val_loss: 9.8287 - val_acc: 0.2563
Epoch 3/20
6680/6680 [==============================] - 5s - loss: 10.4984 - acc: 0.2238 - val_loss: 8.8753 - val_acc: 0.3150
Epoch 4/20
6680/6680 [==============================] - 5s - loss: 9.7672 - acc: 0.2740 - val_loss: 8.5092 - val_acc: 0.3749
Epoch 5/20
6680/6680 [==============================] - 5s - loss: 9.1936 - acc: 0.3162 - val_loss: 8.3399 - val_acc: 0.3940
Epoch 6/20
6680/6680 [==============================] - 5s - loss: 8.8600 - acc: 0.3491 - val_loss: 8.2590 - val_acc: 0.4060
Epoch 7/20
6680/6680 [==============================] - 5s - loss: 8.6845 - acc: 0.3675 - val_loss: 8.3298 - val_acc: 0.3976
Epoch 8/20
6680/6680 [==============================] - 5s - loss: 8.4987 - acc: 0.3823 - val_loss: 8.1804 - val_acc: 0.4108
Epoch 9/20
6680/6680 [==============================] - 5s - loss: 8.4052 - acc: 0.3957 - val_loss: 8.0841 - val_acc: 0.4240
Epoch 10/20
6680/6680 [==============================] - 5s - loss: 8.3220 - acc: 0.4036 - val_loss: 8.2251 - val_acc: 0.4096
Epoch 11/20
6680/6680 [==============================] - 5s - loss: 8.2250 - acc: 0.4120 - val_loss: 8.0891 - val_acc: 0.4192
Epoch 12/20
6680/6680 [==============================] - 6s - loss: 8.1274 - acc: 0.4249 - val_loss: 8.1342 - val_acc: 0.4204
Epoch 13/20
6680/6680 [==============================] - 5s - loss: 8.0921 - acc: 0.4287 - val_loss: 8.0639 - val_acc: 0.4335
Epoch 14/20
6680/6680 [==============================] - 5s - loss: 8.0179 - acc: 0.4350 - val_loss: 7.9949 - val_acc: 0.4335
Epoch 15/20
6680/6680 [==============================] - 5s - loss: 7.9217 - acc: 0.4436 - val_loss: 7.9982 - val_acc: 0.4299
Epoch 16/20
6680/6680 [==============================] - 5s - loss: 7.9092 - acc: 0.4460 - val_loss: 7.9653 - val_acc: 0.4251
Epoch 17/20
6680/6680 [==============================] - 5s - loss: 7.8168 - acc: 0.4528 - val_loss: 8.0577 - val_acc: 0.4204
Epoch 18/20
6680/6680 [==============================] - 5s - loss: 7.8022 - acc: 0.4536 - val_loss: 7.9334 - val_acc: 0.4491
Epoch 19/20
6680/6680 [==============================] - 5s - loss: 7.7870 - acc: 0.4570 - val_loss: 7.8972 - val_acc: 0.4479
Epoch 20/20
6680/6680 [==============================] - 5s - loss: 7.7736 - acc: 0.4578 - val_loss: 7.9003 - val_acc: 0.4443
Test accuracy: 44.3780%
Using network based on VGG19
----------
Assessing file 'images/Labrador_retriever_06455.jpg'
Labrador_retriever
----------
Assessing file 'images/sample_dog_output.png'
American_staffordshire_terrier
----------
Assessing file 'images/Human_Pam.jpg'
Pomeranian
----------
Assessing file 'images/Dog_Daschund.jpg'
Basset_hound
----------
Assessing file 'images/dog_on_humans.jpg'
Xoloitzcuintli
----------
Assessing file 'images/human_chris.jpg'
Brittany
----------
Assessing file 'images/sample_cnn.png'
Brussels_griffon
----------
Assessing file 'images/Labrador_retriever_06457.jpg'
Labrador_retriever
----------
Assessing file 'images/Welsh_springer_spaniel_08203.jpg'
Welsh_springer_spaniel
----------
Assessing file 'images/sample_human_output.png'
Havanese
----------
Assessing file 'images/Curly-coated_retriever_03896.jpg'
Curly-coated_retriever
----------
Assessing file 'images/American_water_spaniel_00648.jpg'
Portuguese_water_dog
----------
Assessing file 'images/Brittany_02625.jpg'
Brittany
----------
Assessing file 'images/human_holding_dog.jpg'
Chinese_crested
----------
Assessing file 'images/Labrador_retriever_06449.jpg'
Labrador_retriever
already trained Resnet50
******************************
Creating network based on InceptionV3
******************************
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_4 ( (None, 2048)              0         
_________________________________________________________________
dropout_5 (Dropout)          (None, 2048)              0         
_________________________________________________________________
dense_6 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 10s - loss: 15.7220 - acc: 0.0115 - val_loss: 15.7912 - val_acc: 0.0084
Epoch 2/20
6680/6680 [==============================] - 5s - loss: 15.7744 - acc: 0.0132 - val_loss: 15.7433 - val_acc: 0.0108
Epoch 3/20
6680/6680 [==============================] - 5s - loss: 15.7526 - acc: 0.0132 - val_loss: 15.8392 - val_acc: 0.0084
Epoch 4/20
6680/6680 [==============================] - 5s - loss: 15.7211 - acc: 0.0147 - val_loss: 15.6520 - val_acc: 0.0180
Epoch 5/20
6680/6680 [==============================] - 5s - loss: 15.6530 - acc: 0.0183 - val_loss: 15.7194 - val_acc: 0.0120
Epoch 6/20
6680/6680 [==============================] - 5s - loss: 15.6856 - acc: 0.0148 - val_loss: 15.7928 - val_acc: 0.0156
Epoch 7/20
6680/6680 [==============================] - 5s - loss: 15.6424 - acc: 0.0180 - val_loss: 15.5643 - val_acc: 0.0156
Epoch 8/20
6680/6680 [==============================] - 6s - loss: 15.6320 - acc: 0.0172 - val_loss: 15.6442 - val_acc: 0.0180
Epoch 9/20
6680/6680 [==============================] - 5s - loss: 15.6465 - acc: 0.0190 - val_loss: 15.6317 - val_acc: 0.0180
Epoch 10/20
6680/6680 [==============================] - 5s - loss: 15.6407 - acc: 0.0183 - val_loss: 15.6815 - val_acc: 0.0132
Epoch 11/20
6680/6680 [==============================] - 5s - loss: 15.6212 - acc: 0.0205 - val_loss: 15.6652 - val_acc: 0.0168
Epoch 12/20
6680/6680 [==============================] - 5s - loss: 15.5978 - acc: 0.0216 - val_loss: 15.6112 - val_acc: 0.0132
Epoch 13/20
6680/6680 [==============================] - 5s - loss: 15.5774 - acc: 0.0205 - val_loss: 15.5397 - val_acc: 0.0204
Epoch 14/20
6680/6680 [==============================] - 5s - loss: 15.4930 - acc: 0.0277 - val_loss: 15.6994 - val_acc: 0.0156
Epoch 15/20
6680/6680 [==============================] - 5s - loss: 15.5446 - acc: 0.0262 - val_loss: 15.7401 - val_acc: 0.0180
Epoch 16/20
6680/6680 [==============================] - 5s - loss: 15.5269 - acc: 0.0266 - val_loss: 15.5693 - val_acc: 0.0204
Epoch 17/20
6680/6680 [==============================] - 5s - loss: 15.5201 - acc: 0.0251 - val_loss: 15.5749 - val_acc: 0.0168
Epoch 18/20
6680/6680 [==============================] - 5s - loss: 15.5277 - acc: 0.0257 - val_loss: 15.7143 - val_acc: 0.0120
Epoch 19/20
6680/6680 [==============================] - 5s - loss: 15.5219 - acc: 0.0263 - val_loss: 15.6088 - val_acc: 0.0228
Epoch 20/20
6680/6680 [==============================] - 6s - loss: 15.4936 - acc: 0.0280 - val_loss: 15.6005 - val_acc: 0.0168
Test accuracy: 1.7943%
Using network based on InceptionV3
----------
Assessing file 'images/Labrador_retriever_06455.jpg'
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.5/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5
Norwich_terrier
----------
Assessing file 'images/sample_dog_output.png'
Norwich_terrier
----------
Assessing file 'images/Human_Pam.jpg'
Norwich_terrier
----------
Assessing file 'images/Dog_Daschund.jpg'
Norwich_terrier
----------
Assessing file 'images/dog_on_humans.jpg'
French_bulldog
----------
Assessing file 'images/human_chris.jpg'
Norwich_terrier
----------
Assessing file 'images/sample_cnn.png'
Italian_greyhound
----------
Assessing file 'images/Labrador_retriever_06457.jpg'
Norwich_terrier
----------
Assessing file 'images/Welsh_springer_spaniel_08203.jpg'
French_bulldog
----------
Assessing file 'images/sample_human_output.png'
Belgian_malinois
----------
Assessing file 'images/Curly-coated_retriever_03896.jpg'
Norwich_terrier
----------
Assessing file 'images/American_water_spaniel_00648.jpg'
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-35-ee94b47cf858> in <module>()
     13     load_weights(network)
     14     test_model_accuracy(network)
---> 15     test_algorithm(network)

<ipython-input-34-8527a0b69ed1> in test_algorithm(network, directory)
      6     for test_image in test_images:
      7         print("-"*10+"\nAssessing file '{}'".format(test_image))
----> 8         what_dog_breed(test_image, network)
      9         print()
     10 test_algorithm(network)

<ipython-input-33-b5a387003345> in what_dog_breed(img_path, network)
     16         ax.set_title('No dog or human detected!\nTrying anyway...')
     17     # display prediction
---> 18     prediction = predict_breed(img_path, network)
     19     ax.set_xlabel('Detected dog breed is {}'.format(prediction))
     20     print(prediction)

<ipython-input-32-527f14205abe> in predict_breed(img_path, network)
      4     extract_model = [extract_VGG16,extract_VGG19,extract_Resnet50,extract_InceptionV3,extract_Xception]                        [all_networks.index(network)]
      5     # extract bottleneck features
----> 6     bottleneck_feature = extract_model(path_to_tensor(img_path))
      7     # obtain predicted vector
      8     predicted_vector = model_[network].predict(bottleneck_feature)

/home/cbc/dev/aind/dog-project/extract_bottleneck_features.py in extract_InceptionV3(tensor)
     17 def extract_InceptionV3(tensor):
     18         from keras.applications.inception_v3 import InceptionV3, preprocess_input
---> 19         return InceptionV3(weights='imagenet', include_top=False).predict(preprocess_input(tensor))

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/keras/applications/inception_v3.py in InceptionV3(include_top, weights, input_tensor, input_shape, pooling, classes)
    381                 cache_subdir='models',
    382                 md5_hash='bcbd6486424b2319ff4ef7d526e38f63')
--> 383         model.load_weights(weights_path)
    384         if K.backend() == 'theano':
    385             convert_all_kernels_in_model(model)

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/keras/engine/topology.py in load_weights(self, filepath, by_name)
   2493             load_weights_from_hdf5_group_by_name(f, self.layers)
   2494         else:
-> 2495             load_weights_from_hdf5_group(f, self.layers)
   2496 
   2497         if hasattr(f, 'close'):

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/keras/engine/topology.py in load_weights_from_hdf5_group(f, layers)
   2906                              ' elements.')
   2907         weight_value_tuples += zip(symbolic_weights, weight_values)
-> 2908     K.batch_set_value(weight_value_tuples)
   2909 
   2910 

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in batch_set_value(tuples)
   1995             assign_ops.append(assign_op)
   1996             feed_dict[assign_placeholder] = value
-> 1997         get_session().run(assign_ops, feed_dict=feed_dict)
   1998 
   1999 

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in get_session()
    151         session = _SESSION
    152     if not _MANUAL_VAR_INIT:
--> 153         _initialize_variables()
    154     return session
    155 

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in _initialize_variables()
    304     if uninitialized_variables:
    305         sess = get_session()
--> 306         sess.run(tf.variables_initializer(uninitialized_variables))
    307 
    308 

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    787     try:
    788       result = self._run(None, fetches, feed_dict, options_ptr,
--> 789                          run_metadata_ptr)
    790       if run_metadata:
    791         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    995     if final_fetches or final_targets:
    996       results = self._do_run(handle, final_targets, final_fetches,
--> 997                              feed_dict_string, options, run_metadata)
    998     else:
    999       results = []

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1130     if handle is None:
   1131       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1132                            target_list, options, run_metadata)
   1133     else:
   1134       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1137   def _do_call(self, fn, *args):
   1138     try:
-> 1139       return fn(*args)
   1140     except errors.OpError as e:
   1141       message = compat.as_text(e.message)

/home/cbc/anaconda3/envs/aind/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1119         return tf_session.TF_Run(session, options,
   1120                                  feed_dict, fetch_list, target_list,
-> 1121                                  status, run_metadata)
   1122 
   1123     def _prun_fn(session, handle, feed_dict, fetch_list):

KeyboardInterrupt: 
In [ ]:
# re-test algorithms
# for network in all_networks:
#     test_algorithm(network)  
In [ ]: